<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-03-20
 * Time: 18:12
 */
namespace app\admin\controller;

use think\Db;
use think\Exception;

class Stock extends Base
{
    protected static $err_code = 0;
    /**
     * 空操作
     */
    public function _empty(){
        $this->redirect('admin/login');
    }

    /**
     * 库存列表
     */
    public function stock_list(){
        $page_param = input('param.');
        if (isset($page_param['page']) && $page_param['page'] > 0)
            unset($page_param['page']);
        $shop_id = input('param.shop_name',0); //店铺id
        $cate_id = input('param.cate',0); //类别id
        $tuijian = input('param.tuijian',2); //推荐类型
        $this->assign('tuijian',$tuijian);
        $this->assign('cate_id',$cate_id);
        $this->assign('shop_id',$shop_id);
        $where=[];
        if ($shop_id != 0){
            $where['a.shop_id']= $shop_id;
        }
        if ($cate_id != 0){
            $where['a.cat_id']= $cate_id;
        }
        if ($tuijian != 2){
            $where['a.tuijian']= $tuijian;
        }
        $goods_list = Db::table('yf_goods')->alias('a')
            ->field('a.id,a.cat_id,a.goods_name,a.shop_id,a.shoptype,a.store_count,a.last_update,a.tuijian,b.name cat_name,c.shop_name,original_img,price,source_url')
            ->join('yf_items_cate b','a.cat_id=b.id','left')
            ->join('yf_shop c','a.shop_id=c.id','left')
            ->where($where)
            ->order('a.id desc')->paginate(20, false, ['query' => $page_param]); //获取全部商品

//        if ($shop_id == 0){
//            $goods_list = Db::table('yf_goods')->alias('a')
//                ->field('a.id,a.cat_id,a.goods_name,a.shop_id,a.store_count,b.name cat_name,c.shop_name,original_img,price,source_url')
//                ->join('yf_items_cate b','a.cat_id=b.id','left')
//                ->join('yf_shop c','a.shop_id=c.id','left')
//                ->order('a.id desc')->paginate(20, false, ['query' => $page_param]); //获取全部商品
//        }else{
//            $goods_list = Db::table('yf_goods')->alias('a')
//                ->field('a.id,a.cat_id,a.goods_name,a.shop_id,a.store_count,b.name cat_name,c.shop_name,original_img,price,source_url')
//                ->join('yf_items_cate b','a.cat_id=b.id','left')
//                ->join('yf_shop c','a.shop_id=c.id','left')
//                ->where(['a.shop_id'=>$shop_id])
//                ->order('a.id desc')->paginate(20, false, ['query' => $page_param]); //获取指定店铺商品
//        }
        //分页信息
        $page = $goods_list->render();
        $goods_list = $goods_list->toArray();
        $this->assign('goods_list',$goods_list['data']);
        $this->assign('page',$page);
        $items_cate = Db::name('items_cate')->field('id,name')->select();
        $this->assign('cate',$items_cate);
        $shop_list = db('shop')->field('id,shop_name')->where(['status'=>1])->order('id desc')->select(); //店铺列表
        $this->assign('shop_list',$shop_list);
        return $this->fetch();
    }

    /**
     * 商品编辑
     */
    public function stock_edit(){
        if ($this->request->isPost()){
            //开启事务
            Db::startTrans();
            try{
                $data['id'] = input('param.goods_id',0); //商品id
                if ($data['id'] == 0){
                    throw new Exception('商品id未传');
                }
                $data['goods_name'] = input('param.goods_name',''); //商品标题
                $data['price'] = input('param.price',0); //商品价格
                $data['tb_id'] = input('param.tb_id',0); //商品淘宝id
                $data['activity_type'] = input('param.activity_type/a','') == ''? '': implode(',',input('param.activity_type/a','')); //活动类型
                $data['original_img'] = input('param.original_img',''); //商品图片链接
                $data['shoptype'] = input('param.shoptype','C');//商品所属商店类型
                $data['cat_id'] = input('param.cat_id',0);//商品类型
                $data['tuijian'] = input('param.tuijian',0);//推荐
                $data['sales_sum'] = input('param.sales_sum',0);//商品月销量
                $data['store_count'] = input('param.store_count',0); //库存
                $data['sort'] = input('param.sort',50);//商品排序
                $data['is_on_sale'] = input('param.is_on_sale',0);//是否上架
                $data['is_hot'] = input('param.is_hot',0);//是否热卖
                $data['shop_id'] = input('param.shop_id',0); //店铺
                if ($data['shop_id'] == 0 || $data['shop_id'] ==''){
                    throw new Exception('请选择店铺');
                }
                if ($data['shoptype'] == ''){
                    throw new Exception('请选择天猫或者淘宝');
                }
                if ($data['cat_id'] == 0){
                    throw new Exception('商品类型未选择');
                }
                if ($data['shoptype'] == 'B'){
                    $data['source_url'] = 'https://detail.tmall.com/item.htm?id='.$data['tb_id'];
                }else{
                    $data['source_url'] = 'https://item.taobao.com/item.htm?id='.$data['tb_id'];
                }
                $data['last_update'] = time(); //添加时间
                Db::table('yf_goods')->update($data);
                //事务提交
                Db::commit();
                return json(['code'=>200,'msg'=>'success']);
            }catch (Exception $e){
                //事务回滚
                Db::rollback();
                return json(['code'=>0,'msg'=>$e->getMessage()]);
            }
        }else{
            $goods_info=Db::name('goods')->where(array('id'=>input('goods_id')))->find();
            $items_cate = Db::name('items_cate')->field('id,name')->select();
            $this->assign('cate',$items_cate);
            if ($goods_info){
                $goods_info['original_img'] = get_img_url($goods_info['original_img']);
                if (empty($goods_info['source_url'])){
                    $goods_info['source_url'] = $goods_info['shoptype'] == 'B'? 'https://detail.tmall.com/item.htm?id='.$goods_info['tb_id'] :'https://item.taobao.com/item.htm?id='.$goods_info['tb_id'];
                }
            }
            $shop_list =  Db::name('shop')->field('id,shop_name')->where(['status'=>1])->select();
            $this->assign('shops',$shop_list);
            $this->assign('data',$goods_info);
            // 渲染模板输出
            return $this->fetch();
        }
    }


    //商品删除
    public function goods_del(){
        $goods_id=input('goods_id','','intval');
        Db::startTrans();
        try{
            if (!is_numeric($goods_id)){
                throw new Exception('商品id错误');
            }
            $rst=Db::name('goods')->where('id',$goods_id)->delete();
            if($rst!==false){
                Db::commit();
                return json(['code'=>200,'msg'=>'商品删除成功']);
            }else{
                throw new Exception('商品删除失败');
            }
        }catch (Exception $e){
            Db::rollback();
            return json(['code'=>0,'msg'=>$e->getMessage()]);
        }
    }

    /**
     * 入库
     */
    public function stock_add(){
        return $this->fetch();
    }

    /**
     * 根据运单号查找商品相关信息
     */
    public function ajax_get_goodsinfo(){
        $express_num = input('param.express_num',0);
        if ($express_num == 0){
            return json(['code'=>201,'msg'=>'运单号不能为空']);
        }
        $goods_info = Db::table('yf_member_task')->alias('a')->field('a.id,a.purchase_id,a.spec_name,a.tb_id,b.img_url,b.goods_name,c.shop_name')->join('yf_purchase b','a.purchase_id=b.id','left')->join('yf_shop c','b.shop=c.id','left')->where(['a.courier_sn'=>$express_num])->find();
        if ($goods_info){
            return json(['code'=>200,'data'=>$goods_info,'msg'=>'success']);
        }else{
            return json(['code'=>0,'data'=>$goods_info,'msg'=>'success']);
        }
    }

    /**
     * 入库
     */
    public function ajax_finish(){

        //启动事物
        Db::startTrans();
        try{
            $member_task = input('param.member_task',0);
            if ($member_task == 0){
                self::$err_code = 0;
                throw new Exception('参数错误');
            }
            $is_existence = Db::table('yf_member_task')->alias('a')
                ->field('b.id purchase_id,b.waiting_storage all_waiting,b.already_storage all_already,b.tb_id,b.shop,c.waiting_storage,c.already_storage,c.id demand_id')
                ->join('yf_purchase b','a.purchase_id','left')
                ->join('yf_demands c','a.demand_id=c.id','left')
                ->where(['a.id'=>$member_task])->find();
            if ($is_existence){
                if (Db::table('yf_member_task')->where(['id'=>$member_task])->update(['status'=>4])){
                    $goods_info = Db::table('yf_goods')->where(['shop_id'=>$is_existence['shop'],'tb_id'=>$is_existence['tb_id']])->find(); //查找商品表中是否已有该商品
                    if ($goods_info){
                        Db::table('yf_goods')->where(['id'=>$goods_info['id']])->setInc('store_count'); //商品表库存加1
                        Db::table('yf_goods_spec')->where(['id'=>$goods_info['']]);

                    }else{

                    }
                    Db::table('yf_purchase')->where(['id'=>$is_existence['purchase_id']])->update(['waiting_storage'=>$is_existence['all_waiting']-1,'already_storage'=>$is_existence['all_already']+1]);
                    Db::table('yf_demands')->where(['id'=>$is_existence['demand_id']])->update(['waiting_storage'=>$is_existence['waiting_storage']-1,'already_storage'=>$is_existence['already_storage']+1]);
                    Db::commit();
                    return json(['code'=>200,'msg'=>'success']);
                }else{
                    self::$err_code = 0;
                    throw new Exception('数据更新失败');
                }
            }

        }catch (Exception $e){
            //回滚事物
            Db::rollback();
            return json(['code'=>self::$err_code,'msg'=>$e->getMessage()]);
        }
    }

    /**
     * 商品推荐与取消
     */
    public function set_tuijian(){
        $goods_id = input('param.goods_id',0);
        $tuijian = input('param.tuijian',0);
        Db::startTrans();
        try{
            if ($goods_id == 0){
                throw new Exception('参数错误，商品id有误');
            }
            if (Db::name('goods')->where('id',$goods_id)->setField('tuijian',$tuijian)){
                Db::commit();
                return json(['code'=>200,'msg'=>'设置成功']);
            }else{
                throw new Exception('设置失败');
            }
        }catch (Exception $e){
            Db::rollback();
            return json(['code'=>0,'msg'=>$e->getMessage()]);
        }
    }

    public function stock_choose(){
        return $this->fetch();
    }

}